package ch05.tree_grammar;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.RuleReturnScope;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

import java.io.IOException;

/**
 * 运行程序，在命令行种分别输入
 * x = 3+4
 * print x * [2, 3, 4]
 * 然后按Ctrl-D结束命令行输入
 */
public class Test {
    public static void main(String[] args) throws IOException, RecognitionException {
        // create lexer/parser to build trees from stdin
        VecMathLexer lex = new VecMathLexer(new ANTLRInputStream(System.in));
        CommonTokenStream tokens = new CommonTokenStream(lex);
        VecMathParser p = new VecMathParser(tokens);
        RuleReturnScope r = p.prog();       // 从起始规则开始解析
        // 返回解析好的树
        CommonTree tree = (CommonTree) r.getTree();
        System.out.println(tree.toStringTree());        // print out LISP style

        // serialize tree into node stream
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
        Printer tp = new Printer(nodes);                // create tree walker（创建树的遍历器）
        tp.prog();                                      // 从起始规则开始运行
    }
}
